package com.home.activities;

import org.json.JSONObject;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.home.broadcastreceivers.NotificationReceiver;
import com.home.constants.Consts;
import com.home.jsonhelpers.JsonRequestObject;
import com.home.rhclient.MainController;
import com.home.rhtester.R;

public class ResourceActivity extends AdvanceActivity {

	TextView resourceNameView, resourceDescriptionView, activeTimeMessage, activeTime;
	Button startButton, restartButton, plusButton, minusButton;
	TextView reservTimeView;

	private JSONObject resourceJson;
	private long resourceId;
	private int reservationTimeIndex = 0;
	private boolean resourceActive = false;
	public boolean resourceOwned=false;
	private ResourceActivityTimer timerTask;
	private Handler timerHandler;
	private String sResourceName, sResourceDescription, jsonString;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		resourceActive = false;
		
		
		
		timerHandler = new Handler();

		jsonString = savedInstanceState != null ? savedInstanceState.getString(Consts.RESOURCE_RAW_DATA) : null;
		if (jsonString == null) {
			Bundle extras = getIntent().getExtras();
			jsonString = extras != null ? extras.getString(Consts.RESOURCE_RAW_DATA) : null;
		}

		try {
			
			
			if (jsonString != null) {
				resourceJson=new JSONObject(jsonString);
				sResourceName = resourceJson.getString(Consts.RESOURCE_NAME);
				resourceId = resourceJson.getLong(Consts.RESOURCE_ID);
				sResourceDescription = resourceJson.getString(Consts.RESOURCE_DESCRIPTION);
				resourceJson = new JSONObject(jsonString);
			
				int resourceState=resourceJson.getInt(Consts.RESOURCE_STATE);
				if (resourceState==Consts.RESOURCE_ACTIVE)
				{
					int ownership=resourceJson.getInt(Consts.RESOURCE_OWNERSHIP);
					if (ownership==Consts.RESOURCE_OWNED)
					{
						resourceOwned=true;
						setContentView(R.layout.resourcedetaillayout);
						setViews();
						updateTimerView();
					}
					else
					{
						resourceOwned=false;
						setContentView(R.layout.resourcedetaillayout_unavailable);
						setViewsMinimal();
						//need to refresh the resource list for the cases when it was outdated when selecting the resource
						setResult(Consts.RESULT_REFRESH_REQUESTED, new Intent());
					}
				}
				else
				{
					    setContentView(R.layout.resourcedetaillayout);
					    setViews();
					    updateTimerView();
						resourceActive=false;
						resourceOwned=false;
				}

				
			
			}
			JsonRequestObject requestJsonObj = new JsonRequestObject(getApplicationContext());
			requestJsonObj.put(Consts.RESOURCE_ID, resourceId);
			MainController.GetInstance().restConnector.requestResourceDetail(requestJsonObj.getJsonObject(), this);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	public void setUnavailableStateOnDetailsRequest()
	{
		
		resourceOwned=false;
		setContentView(R.layout.resourcedetaillayout_unavailable);
		setViewsMinimal();
		//need to refresh the resource list for the cases when it was outdated when selecting the resource
		setResult(Consts.RESULT_REFRESH_REQUESTED, new Intent());

	}
	public void setAvailableStateOnDetailsRequest()
	{
		setContentView(R.layout.resourcedetaillayout);
	    setViews();
	    updateTimerView();
		resourceActive=false;
		resourceOwned=false;
	}

	private void updateTimerView() {
		reservTimeView.setText(String.valueOf(Consts.RESERVATION_TIMERS[reservationTimeIndex]));
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (resourceActive)
		{
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.listview_menu, menu);
			MenuItem restart=menu.findItem(R.id.resfresh_list);
			restart.setTitle(R.string.restart);
		}
		
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.resfresh_list:
			try {
				
				JsonRequestObject requestObject = new JsonRequestObject(getApplicationContext());
				requestObject.put(Consts.RESOURCE_ID, resourceId);
				requestObject.put(Consts.RESOURCE_START_MODE, Consts.RESOURCE_RESTART);

				MainController.GetInstance().restConnector.restartResource(requestObject.getJsonObject(), this);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		}
		return true;
	}

	public void startNotificationService(long reservationLength) {
		AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
		long notifyBefore = 1000L * 60L * 5L;// TODO replace with a configurable
												// value

		Log.v("startNotificationService", "Starting Service: raw_data: " + jsonString + " reservationLength: " + reservationLength);
		Intent notificationIntent = new Intent(this, NotificationReceiver.class);
		notificationIntent.putExtra(Consts.RESOURCE_RAW_DATA, jsonString);
		notificationIntent.putExtra(Consts.RESOURCE_NAME, sResourceName);
		notificationIntent.putExtra(Consts.NOTIFY_BEFORE, notifyBefore);

		long notifyAt = System.currentTimeMillis() + reservationLength - notifyBefore;
		PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT);
		am.set(AlarmManager.RTC_WAKEUP, notifyAt, pendingIntent);
	}

	private void setViews() {
		setViewsMinimal();
		
		startButton = (Button) findViewById(R.id.start_resource_button);
		plusButton = (Button) findViewById(R.id.startspinnerplus);
		minusButton = (Button) findViewById(R.id.startspinnerminus);
		reservTimeView = (TextView) findViewById(R.id.startspinner);
		restartButton = (Button) findViewById(R.id.restart_resource_button);
		restartButton.setVisibility(Button.INVISIBLE);

		startButton.setOnClickListener(new StartButtonClickListener(this));

		SpinnerClickListener spinnerListener = new SpinnerClickListener();
		plusButton.setOnClickListener(spinnerListener);
		minusButton.setOnClickListener(spinnerListener);
	}
	private void setViewsMinimal()
	{
		resourceNameView = (TextView) findViewById(R.id.resourcename);
		resourceDescriptionView = (TextView) findViewById(R.id.resourcedescription);
		activeTimeMessage = (TextView) findViewById(R.id.active_resource_time_message);
		activeTime = (TextView) findViewById(R.id.activeTime);
		resourceNameView.setText(sResourceName);
		resourceDescriptionView.setText(sResourceDescription);
	}

	class SpinnerClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			if (v == plusButton) {
				navigateReservationTime(1);
			}
			if (v == minusButton) {
				navigateReservationTime(-1);
			}

		}

	}

	private void navigateReservationTime(int navAmount) {
		if (reservationTimeIndex + navAmount >= Consts.RESERVATION_TIMERS.length) {
			reservationTimeIndex = 0;
		} else if (reservationTimeIndex + navAmount < 0) {
			reservationTimeIndex = Consts.RESERVATION_TIMERS.length - 1;
		} else {
			reservationTimeIndex += navAmount;
		}
		updateTimerView();

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		Log.v("saveState", "saving state: "+resourceActive);
		super.onSaveInstanceState(outState);
		outState.putString(Consts.RESOURCE_RAW_DATA, jsonString);
		
	//	timerHandler.removeCallbacksAndMessages(null);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);

	}

	class StartButtonClickListener implements OnClickListener {

		ResourceActivity resourceActivity;

		public StartButtonClickListener(ResourceActivity resActivity) {
			resourceActivity = resActivity;
		}

		@Override
		public void onClick(View v) {
			try {
				JsonRequestObject requestObject = new JsonRequestObject(getApplicationContext());
				requestObject.put(Consts.RESOURCE_ID, resourceId);
				requestObject.put(Consts.RESERVATION_LENGTH, Consts.RESERVATION_TIMERS[reservationTimeIndex]);
				requestObject.put(Consts.RESOURCE_START_MODE, Consts.RESOURCE_START);

				MainController.GetInstance().restConnector.startResource(requestObject.getJsonObject(), resourceActivity);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	class RestartButtonClickListener implements OnClickListener {

		ResourceActivity resourceActivity;

		public RestartButtonClickListener(ResourceActivity resActivity) {
			resourceActivity = resActivity;
		}

		@Override
		public void onClick(View v) {
			try {
				JsonRequestObject requestObject = new JsonRequestObject(getApplicationContext());
				requestObject.put(Consts.RESOURCE_ID, resourceId);
				requestObject.put(Consts.RESOURCE_START_MODE, Consts.RESOURCE_RESTART);

				MainController.GetInstance().restConnector.restartResource(requestObject.getJsonObject(), resourceActivity);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	public void showRestartButton() {
		restartButton.setVisibility(Button.VISIBLE);
		startButton.setVisibility(Button.INVISIBLE);
		resourceActive = true;
	}

	public void updateResourceTimer(long clientServerDelta, long activationLength) {

		Log.v("updateResourceTimer", "Current Time: " + MainController.GetInstance().GetCurrentDate().toGMTString());
		Log.v("updateResourceTimer", "Activation Length: " + activationLength + "Server-Client DIff: " + clientServerDelta);
		timerTask = new ResourceActivityTimer(MainController.GetInstance().GetCurrentDate().getTime(), activationLength - clientServerDelta);
		timerHandler.removeCallbacksAndMessages(null);
		timerHandler.post(timerTask);
		activeTime.setVisibility(View.VISIBLE);
		activeTimeMessage.setVisibility(View.VISIBLE);

	}

	private class ResourceActivityTimer implements Runnable {
		private long startTime;
		private long reservationLength;
		private int seconds, minutes, hours;
		public long timeLeft;

		public ResourceActivityTimer(long startTime, long timeLeft) {
			this.startTime = startTime;
			this.reservationLength = timeLeft;

		}

		@Override
		public void run() {
			timeLeft = reservationLength - (MainController.GetInstance().GetCurrentDate().getTime() - startTime);
			if (timeLeft > 0) {
				activeTimeMessage.setVisibility(View.VISIBLE);
				seconds = (int) (timeLeft / 1000);
				minutes = seconds / 60;
				hours = minutes / 60;

				seconds = seconds % 60;
				minutes = minutes % 60;
				activeTime.setText(String.format("%d:%02d:%02d", hours, minutes, seconds));
				timerHandler.postDelayed(this, 200);
			} else {
				activeTime.setVisibility(View.INVISIBLE);
				activeTimeMessage.setVisibility(View.INVISIBLE);
				resourceActive = true;
				setResult(Consts.RESULT_REFRESH_REQUESTED, new Intent());
				finish();
			}

		}

	}

}
